<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\brandActivity\SmallActivity as mSmallActivity;
use Biz\model\brandActivity\SmallActivityLottery as mSmallActivityLottery;
use Doraemon\service\User;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\LinkFormat;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class SmallActivityController extends Controller
{

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function list(Content $content)
    {
        Admin::script(self::closeScript());
        $list = mSmallActivity::selectByWhere(['ORDER' => ['id' => 'DESC']]);
        foreach ($list as &$v) {
            if (empty($v['link_url'])) $v['link_url'] = LinkFormat::generateSingleLink($v['link_type'], $v['link_params']);
        }
        $gridModel = new pGridDataModel($list);
        $gridList = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->column('id');
            $grid->column('activity_title', '活动标题');
            $grid->column('sub_title', '副标题');
            $grid->column('cover_img', '活动图片')->image(100, 100)->display(function () {
                $url = $this->cover_img ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $this->cover_img, ImgUrl::IMAGE_SIZE_OP_ORI) : '';
                return '<img src="' . $url . '" style="max-width:100px;max-height:200px" class="img img-thumbnail">';
            });
            $grid->column('link_url', '跳转地址')->width(400)->copyable();
            $grid->column('activity_state', '活动状态')->display(function () {
                return mSmallActivity::STATE_DESC[$this->activity_state];
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                if ($actions->row->activity_state != mSmallActivity::STATE_CLOSE) {
                    $actions->prepend('<a class="fa fa-trash offline-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">结束此活动</a>');
                }
                $actions->prepend('<a class="fa fa-envelope" href="' . url('/admin/brand/smallactivity/' . $actions->row->id . '/lottery') . '">编辑获奖名单</a>');
            });
        });
        return $content->header('小活动管理列表')->row($gridList);
    }

    /**
     *
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function edit(Content $content, $id = 0)
    {
        $info = [];
        if ($id) {
            $info = mSmallActivity::getByWhere(['id' => $id]);
            if ($info) {
                $info['link'] = [
                    'link_type' => $info['link_type'],
                    'link_params' => $info['link_params'],
                ];
            }
        }
        $form = new Form($info);
        $form->hidden('id', 'id');
        $form->text('activity_title', '标题')->rules('required|min:1');
        $form->text('sub_title', '副标题')->rules('required|min:1');
        $form->imgUpload('cover_img', '图片');
        $form->text('link_url', '跳转链接')->help('此[跳转链接]优先级高于链接选择器');
        $form->linkSelect('link', '跳转链接');
        $form->action(url('/admin/brand/smallactivity/save'));
        return $content->header('编辑活动')
            ->breadcrumb([
                'text' => '小活动管理列表',
                'url' => '/brand/smallactivity'
            ], ['text' => '小活动管理列表'])
            ->row($form);
    }

    public function save(Request $request, Content $content)
    {
        try {
            $params = $request->all();
            $id = $params['id'];
            $data = [
                'activity_title' => $params['activity_title'],
                'sub_title' => $params['sub_title'],
                'cover_img' => $params['cover_img'],
                'link_url' => $params['link_url'],
                'link_type' => $params['link_type'],
                'link_params' => empty($params['link_params']) ? '' : json_encode($params['link_params'], JSON_UNESCAPED_UNICODE),
            ];
            if ($id) {
                mSmallActivity::updateData($data, ['id' => $id]);
            } else {
                mSmallActivity::insertData($data);
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/brand/smallactivity')->with(compact('success'));
    }

    public function close(Request $request, $id = 0)
    {
        try {
            $info = mSmallActivity::getByWhere(['id' => $id]);
            if (!$info) {
                throw new \Exception('活动不存在');
            }
            $uids = mSmallActivityLottery::selectByWhere(['small_activity_id' => $id, 'lottery_state[!]' => mSmallActivityLottery::STATE_DEL], 'uid');
            if (!$uids) {
                throw new \Exception('至少有1个中奖用户才可关闭');
            }
            mSmallActivity::updateData(['activity_state' => mSmallActivity::STATE_CLOSE], ['id' => $id]);
            $success = [
                'message' => '关闭活动: ' . $id . ' 成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'message' => '关闭失败,信息:' . $e->getMessage(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    private function closeScript()
    {
        return <<<SCRIPT
        $('.offline-data').unbind('click').click(function(){
            var id= $(this).data('id');
                let url = '/admin/brand/smallactivity/' +  $(this).data('id')  + '/close'
                let params = {}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
        });
SCRIPT;
    }

    public function lottery(Request $request, Content $content, $id = 0)
    {
        $info = mSmallActivity::getByWhere(['id' => $id]);
        $form = new Form($info);
        $form->text('id', '活动id')->readonly();
        $form->text('activity_title', '活动名称')->readonly();
        $form->text('uid', '用户uid');
        $form->action(url('/admin/brand/smallactivity/' . $id . '/lottery/save'));
        $uids = mSmallActivityLottery::selectByWhere(['small_activity_id' => $id, 'lottery_state[!]' => mSmallActivityLottery::STATE_DEL], 'uid');
        $users = User::getBatchBasicUserInfo($uids);
        foreach ($users as &$row) {
            $row['id'] = $row['uid'];
        }
        $gridModel = new pGridDataModel($users);
        $gridList = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->column('id', 'id');
            $grid->column('uid', 'uid');
            $grid->column('nick', '用户名称');
            $grid->column('avatar', '用户图像')->image(100, 100);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
            });
        });
        return $content->header('活动中奖用户')
            ->breadcrumb([
                'text' => '小活动管理列表',
                'url' => '/brand/smallactivity'
            ], ['text' => '小活动管理列表'])
            ->row($form->render() . $gridList->render());
    }

    public function savelottery(Request $request, Content $content, $id)
    {
        try {
            $uid = $request->input('uid', 0);
            if (!$uid) {
                throw new \Exception('必须输入uid');
            }
            $info = mSmallActivityLottery::getByWhere(['small_activity_id' => $id, 'uid' => $uid]);
            if ($info) {
                mSmallActivityLottery::updateData(['lottery_state' => mSmallActivityLottery::STATE_NORMAL], ['id' => $info['id']]);
            } else {
                mSmallActivityLottery::insertData(['small_activity_id' => $id, 'uid' => $uid, 'lottery_state' => mSmallActivityLottery::STATE_NORMAL]);
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/brand/smallactivity/' . $id . '/lottery')->with(compact('success'));
    }

    public function dellottery(Request $request, Content $content, $id, $uid)
    {
        try {
            $info = mSmallActivityLottery::getByWhere(['small_activity_id' => $id, 'uid' => $uid]);
            if ($info) {
                mSmallActivityLottery::updateData(['lottery_state' => mSmallActivityLottery::STATE_DEL], ['id' => $info['id']]);
            } else {
                throw new \Exception('不存在的信息');
            }
            $success = [
                'title' => '删除用户: ' . $uid . ' 成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '删除失败,信息:' . $e->getFile() . $e->getLine() . $e->getMessage(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

}
